using Avalonia.Controls;
using Avalonia.Interactivity;
using IntegratedMeasuring.Utils;
using IntegratedMeasuring.ViewModels.Scheme;
using IntegratedMeasuring.Storage;
using System;
using System.Linq;
using System.Threading.Tasks;
using Avalonia.Collections;
using System.Collections.Generic;
using System.IO;
using System.Diagnostics;
using Dm.util;

namespace IntegratedMeasuring.Pages;

public partial class OrderManagementPage : UserControl
{
    private DataGridCollectionView? _orderView;

    public OrderManagementPage()
    {
        InitializeComponent();
        Loaded += OnLoaded;
    }

    private async void OnLoaded(object sender, RoutedEventArgs e)
    {
        await LoadOrdersAsync();
    }

    private async Task LoadOrdersAsync()
    {
        try
        {
            var orders = await BaseDataStorage.Instance.LoadProductionOrdersAsync();
            _orderView = new DataGridCollectionView(orders);
            _orderView.GroupDescriptions?.Clear();
            _orderView.GroupDescriptions?.Add(new DataGridPathGroupDescription("Name")); // 按工单名称分组
            OrderDataGrid.ItemsSource = _orderView;
        }
        catch (Exception ex)
        {
            NotificationHelper.ShowError("加载失败", $"加载工单列表失败：{ex.Message}");
        }
    }

    private async void AddOrderButton_Click(object? sender, RoutedEventArgs e)
    {
        var dialog = new OrderEditDialog();
        dialog.CheckOrderBatchExists = (name, batch) =>
        {
            var orders = _orderView?.Cast<ProductionOrder>().ToList() ?? new List<ProductionOrder>();
            return orders.Any(x => x.Name == name && x.BatchNumber == batch);
        };
        dialog.SaveNewBatchAction = async (newOrder) =>
        {
            if (await BaseDataStorage.Instance.SaveProductionOrderAsync(newOrder))
            {
                NotificationHelper.ShowSuccess("操作提示", "新周期保存成功");
                await LoadOrdersAsync();
            }
        };
        var window = this.VisualRoot as Window;
        var result = await dialog.ShowDialog<bool?>(window);
        
        if (result == true && dialog.EditedOrder != null)
        {
            try
            {
                // 校验同工单号下周期号唯一
                var orders = _orderView?.Cast<ProductionOrder>().ToList() ?? new List<ProductionOrder>();
                if (orders.Any(x => x.Name == dialog.EditedOrder.Name && x.BatchNumber == dialog.EditedOrder.BatchNumber))
                {
                    NotificationHelper.ShowError("保存失败", "同工单号下周期号不可重复！");
                    return;
                }
                if (await BaseDataStorage.Instance.SaveProductionOrderAsync(dialog.EditedOrder))
                {
                    NotificationHelper.ShowSuccess("操作提示", "工单创建成功");
                    await LoadOrdersAsync();
                }
            }
            catch (Exception ex)
            {
                NotificationHelper.ShowError("保存失败", $"保存工单失败：{ex.Message}");
            }
        }
    }

    private async void DeleteSelectedButton_Click(object? sender, RoutedEventArgs e)
    {
        var collectionView = OrderDataGrid.ItemsSource as DataGridCollectionView;
        if (collectionView == null) return;
        
        var selected = collectionView.Cast<ProductionOrder>().Where(x => x.IsSelected == true).ToList();
        if (selected.Count == 0)
        {
            NotificationHelper.ShowWarning("操作提示", "请在下方表格选中要操作的项目");
            return;
        }
        
        // 显示确认弹窗
        var confirmDialog = new ConfirmDialog("确认要删除选中的工单吗？删除后不可恢复！");
        var window = this.VisualRoot as Window;
        var result = await confirmDialog.ShowDialog<bool?>(window);
        
        if (result == true)
        {
            try
            {
                foreach (var item in selected)
                {
                    await BaseDataStorage.Instance.DeleteProductionOrderAsync(item.Id);
                }
                NotificationHelper.ShowSuccess("操作提示", "删除成功");
                await LoadOrdersAsync();
            }
            catch (Exception ex)
            {
                NotificationHelper.ShowError("删除失败", $"删除工单失败：{ex.Message}");
            }
        }
    }

    private async void EditButton_Click(object? sender, RoutedEventArgs e)
    {
        if (sender is Button button && button.DataContext is ProductionOrder order)
        {
            var dialog = new OrderEditDialog(order);
            dialog.CheckOrderBatchExists = (name, batch) =>
            {
                var orders = _orderView?.Cast<ProductionOrder>().Where(x => x.Id != order.Id).ToList() ?? new List<ProductionOrder>();
                return orders.Any(x => x.Name == name && x.BatchNumber == batch);
            };
            dialog.SaveNewBatchAction = async (newOrder) =>
            {
                if (await BaseDataStorage.Instance.SaveProductionOrderAsync(newOrder))
                {
                    NotificationHelper.ShowSuccess("操作提示", "新周期保存成功");
                    await LoadOrdersAsync();
                }
            };
            var window = this.VisualRoot as Window;
            var result = await dialog.ShowDialog<bool?>(window);
            
            if (result == true && dialog.EditedOrder != null)
            {
                try
                {
                    // 校验同工单号下周期号唯一（排除自身）
                    var orders = _orderView?.Cast<ProductionOrder>().Where(x => x.Id != order.Id).ToList() ?? new List<ProductionOrder>();
                    if (orders.Any(x => x.Name == dialog.EditedOrder.Name && x.BatchNumber == dialog.EditedOrder.BatchNumber))
                    {
                        NotificationHelper.ShowError("更新失败", "同工单号下周期号不可重复！");
                        return;
                    }
                    // 保持原有的ID和创建时间
                    dialog.EditedOrder.Id = order.Id;
                    dialog.EditedOrder.CreateTime = order.CreateTime;
                    if (await BaseDataStorage.Instance.UpdateProductionOrderAsync(dialog.EditedOrder))
                    {
                        NotificationHelper.ShowSuccess("操作提示", "工单更新成功");
                        await LoadOrdersAsync();
                    }
                }
                catch (Exception ex)
                {
                    NotificationHelper.ShowError("更新失败", $"更新工单失败：{ex.Message}");
                }
            }
        }
    }
    
    private async void ExportPath_Tapped(object? sender, Avalonia.Input.TappedEventArgs e)
    {
        if (sender is TextBlock textBlock && textBlock.Tag is string exportPath)
        {
            if (string.IsNullOrEmpty(exportPath))
            {
                return;
            }
            
            try
            {
                 string directoryPath="";
                // 获取文件路径的目录部分（去掉文件名）
                if (exportPath.indexOf(".") < 0 || exportPath.EndsWith("xlsx"))
                {
                     directoryPath = Path.GetDirectoryName(exportPath);
                }
                else
                {
                    directoryPath = exportPath;
                }

                if (!string.IsNullOrEmpty(directoryPath) && Directory.Exists(directoryPath))
                {
                    // 使用系统默认程序打开文件夹
                    var process = new Process();
                    process.StartInfo.FileName = "explorer.exe";
                    process.StartInfo.Arguments = directoryPath;
                    process.Start();
                }
                else
                {
                    NotificationHelper.ShowWarning("提示", "导出路径不存在或已被删除");
                }
            }
            catch (Exception ex)
            {
                NotificationHelper.ShowError("打开失败", $"无法打开导出路径：{ex.Message}");
            }
        }
    }
} 